<?php
/**
 * ReadingController is the default controller for this application
 * 
 * Notice that we do not have to require 'Zend/Controller/Action.php', this
 * is because our application is using "autoloading" in the bootstrap.
 *
 * @see http://framework.zend.com/manual/en/zend.loader.html#zend.loader.load.autoload
 */
class ReadingController extends Zend_Controller_Action 
{
  
    protected $model;
 
    protected function _getModel()
    {
        if (null === $this->_model) {
            require_once APPLICATION_PATH . '/models/Reading.php';
            $this->_model = new Model_Reading();
        }
        return $this->_model;
    }

    /**
     * The update action is responsible for udpate the temperature readings
     *
     * @return void
     */
    public function indexAction()
    { // http://localhost/ac2/reading?id=2
      // disable layouts for this action:
      $this->_helper->layout->disableLayout();
      
      //$request = $this->getRequest();
      $zone_id = $_REQUEST["id"];
      $reading = $this->_getModel()->fetchLatest($zone_id);
      
      // TBD check to see if the zone_id exists
      if (count($reading) > 0) {
        $reading['created'] = date('D. g:i:s a (l, F n, Y)',strtotime($reading['created']));
        //$reading['created'] = date('g:i:s a (m/d/y)',strtotime($reading['created']));
        //$reading['created'] = date('H:i:s (m.d.y)',strtotime($reading['created']));
        $xml  = "<readings><zone_id>$zone_id</zone_id>";
        $xml .= "<reading>${reading['reading']}</reading>";
        $xml .= "<timestamp>${reading['created']}</timestamp></readings>";
      } else {
        $xml  = "<readings>";
        $xml .= "<zone_id>$zone_id</zone_id>";
        $xml .= "<reading></reading>";
        $xml .= "<timestamp></timestamp>";
        $xml .= "</readings>";
      }  
      header('Content-type: text/xml'); 
      echo $xml;
      exit;
    }
    
    
    public function addAction()
    {
      $request = $this->getRequest();
      $data['zone_id'] = $request->getParam("zone");
      $data['reading'] = $request->getParam("reading");
      
      $this->_getModel()->save($data);
      exit;
    }    
}
